<template>
  <div class="selection-container">
    <h1>选课</h1>

    <!-- 搜索框 -->
    <div class="search-section">
      <label for="search">搜索课程:</label>
      <input type="text" id="search" v-model="searchQuery" @input="filterCourses" placeholder="输入课程名称或教师姓名..." />
    </div>

    <table v-if="filteredCourses.length > 0">
      <thead>
      <tr>
        <th>课程编号</th>
        <th>课程名称</th>
        <th>上课时间</th>
        <th>上课地点</th>
        <th>教师姓名</th>
        <th>剩余名额</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(course, index) in filteredCourses" :key="index">
        <td>{{ course.cno }}</td>
        <td>{{ course.cname }}</td>
        <td>{{ course.time }}</td>
        <td>{{ course.address }}</td>
        <td>{{ course.tname }}</td>
        <td>{{ course.residue }}</td>
        <td>
          <button
              :disabled="!canSelect(course)"
              @click="selectCourse(course)"
          >
            {{ getButtonText(course) }}
          </button>
        </td>
      </tr>
      </tbody>
    </table>
    <p v-else>没有找到匹配的课程。</p>
  </div>
</template>

<script setup>
import axios from 'axios';
import { computed, onMounted, ref } from 'vue';
import { useRoute } from "vue-router";

const route = useRoute();
const id = route.query.id;

// 初始化课程数据
const courses = ref([]);
const studentCourseTimes = ref([]);
const searchQuery = ref('');

// 根据搜索查询过滤课程
const filteredCourses = computed(() => {
  if (!searchQuery.value) return courses.value;
  const queryLower = searchQuery.value.toLowerCase();
  return courses.value.filter(course =>
      course.cname.toLowerCase().includes(queryLower) ||
      course.tname.toLowerCase().includes(queryLower)
  );
});

// 获取课程数据
const getData = async () => {
  try {
    const response = await axios.get('http://localhost:8080/getSecourse', { params: { sno: id } });
    courses.value = response.data;
  } catch (error) {
    console.error(error);
  }
};

// 获取学生已选课程的时间信息
const getStudentCourseTimes = async () => {
  try {
    const response = await axios.get('http://localhost:8080/getStudentCourseTimes', { params: { sno: id } });
    studentCourseTimes.value = response.data;
  } catch (error) {
    console.error(error);
  }
};

// 检查时间是否冲突
const hasTimeConflict = (courseTime) => {
  const parseTime = (time) => {
    const match = /周(\S)(\d+)节/.exec(time);
    return match ? { day: match[1], period: parseInt(match[2], 10) } : null;
  };

  const newCourse = parseTime(courseTime);
  if (!newCourse) return false;

  return studentCourseTimes.value.some(time => {
    const existingCourse = parseTime(time);
    return existingCourse && existingCourse.day === newCourse.day && existingCourse.period === newCourse.period;
  });
};

// 检查是否可以选课
const canSelect = (course) => {
  return course.residue > 0 && !hasTimeConflict(course.time);
};

// 获取按钮文本
const getButtonText = (course) => {
  if (course.residue <= 0) {
    return '已满';
  } else if (hasTimeConflict(course.time)) {
    return '时间冲突';
  } else {
    return '选课';
  }
};

// 选课操作
const selectCourse = (course) => {
  if (!canSelect(course)) {
    alert(hasTimeConflict(course.time) ? '选课时间冲突！' : '此课程已满。');
    return;
  }

  axios.put(`http://localhost:8080/slcourse?cno=${course.cno}&sno=${id}`)
      .then(() => {
        alert('选课成功！');
        getData(); // 重新加载课程数据
        getStudentCourseTimes(); // 更新学生已选课程时间
      })
      .catch(error => {
        console.error(error);
        alert('选课失败，请重试！');
      });
};

// 页面加载时获取数据
onMounted(() => {
  getData();
  getStudentCourseTimes();
});
</script>

<style scoped>
.selection-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
}

.search-section {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
  margin-bottom: 10px;
}

table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
}

th, td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

tr:hover {
  background-color: #f1f1f1;
}

button {
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
  padding: 5px 10px;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: gray;
  cursor: not-allowed;
}
</style>
